import mongoose, { Schema, Document } from 'mongoose';
import { IPaper } from '@shared/types/paper';

export interface IPaperDocument extends Omit<IPaper, '_id'>, Document {}

const paperSchema: Schema = new Schema({
  paper_name: { type: String, required: true },
  question_list: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Question',
    required: true
  }],
  duration: { type: Number, required: true, min: 5, max: 180 }, // 5-180分钟
  total_score: { type: Number }, // 自动计算
  creator: { type: Schema.Types.ObjectId, ref: 'User' },
  create_time: { type: Date, default: Date.now },
  status: { 
    type: String, 
    enum: ['draft', 'published', 'archived'], 
    default: 'draft' 
  },
  description: { type: String }
});

// 计算总分值的中间件
paperSchema.pre('save', async function(next) {
  if (this.isModified('question_list')) {
    const Question = mongoose.model('Question');
    const questions = await Question.find({ _id: { $in: this.question_list } });
    this.total_score = questions.reduce((total, q: any) => total + q.score, 0);
  }
  next();
});

export const Paper = mongoose.model<IPaperDocument>("Paper", paperSchema);
